package cn.seecoder.ai.serviceImpl;

import cn.seecoder.ai.dao.UserRepository;
import cn.seecoder.ai.exception.AIExternalException;
import cn.seecoder.ai.model.po.User;
import cn.seecoder.ai.model.vo.UserVO;
import cn.seecoder.ai.service.UserService;
import cn.seecoder.ai.utils.POJOConverter;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Optional;

/**
 * @author fanyanpeng
 * @date 2023/4/11 0:58
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserRepository userRepository;

    @Override
    public UserVO register(UserVO userVO) {
        String userName = userVO.getUserName();
        String organization = userVO.getOrganization();

        if(organization.isEmpty()){
            throw AIExternalException.userNameNotFound();
        }
        userRepository.findByUserName(userName).ifPresent(user->{
            throw AIExternalException.userNameAlreadyExist();
        });

        User user = toPO(userVO);
        user.setRegisterTime(new Date());
        userRepository.save(user);

        return toVO(user);
    }


    @Override
    public UserVO login(UserVO userVO) {
        String userName = userVO.getUserName();
        String password = userVO.getPassword();


        Optional<User> userOptional = userRepository.findByUserNameAndPassword(userName,password);
        if(!userOptional.isPresent()){
            throw AIExternalException.userNameOrPasswordWrong();
        }
        User user = userOptional.get();
        return toVO(user);
    }


    @Override
    public UserVO getUserVOById(Integer userId){
        if(userId==null){
            log.warn("用户id为null, 查询用户失败, 返回null");
            return null;
        }

        Optional<User> userOptional = userRepository.findById(userId);
        if(!userOptional.isPresent()){
            log.warn("用户id="+userId+", 查询用户失败, 返回null");
            return null;
        }
        User user = userOptional.get();

        // 特殊处理用户密码
        user.setPassword("");
        return toVO(user);

    }


    /**
     * convert a po to vo
     * @author   fanyanpeng
     * @date 2023/4/11 4:39
     * @param user po User
     * @return cn.seecoder.ai.model.vo.UserVO
     */
    UserVO toVO(User user){
        UserVO userVO=new UserVO();
        POJOConverter.convert(user, userVO);
        return userVO;
    }

    /**
     * convert a vo to po
     * @author   fanyanpeng
     * @date 2023/4/11 4:39
     * @param userVO vo User
     * @return cn.seecoder.ai.model.po.User
     */
    User toPO(UserVO userVO){
        User user=new User();
        POJOConverter.convert(userVO, user);
        return user;
    }


}


